import { ref } from 'vue'
import { goDialog, getUUID, getFirstPath, downloadTextFile, selectFile } from '@/utils'
import { domainid, deepCopy } from '@/utils/cloud/utils'
import { DialogEnum } from '@/enums/pluginEnum'
import { ProjectType } from '../../..'
import { getConfigApi, deleteConfigApi, updateConfigApi, uploadDataToGatawayApi } from '@/api/cloud/config.js'
import router from '@/router'
import { PageEnum } from '@/enums/pageEnum'

// 获取datasource

// 数据初始化
export const useDataListInit = () => {
  const getDatasource = () => {
    const pathName = router.currentRoute.value.name
    const firstPath = getFirstPath()
    if (pathName === PageEnum.BASE_HOME_PUBLIC_TEMPLATE_NAME) {
      return 'public_template'
    } else if (pathName === PageEnum.BASE_HOME_TEMPLATE_NAME) {
      return 'template'
    } else if (pathName === PageEnum.BASE_HOME_PROJECT_LIST_NAME) {
      if (firstPath === 'linku') {
        return 'public_project'
      } else {
        return 'project'
      }
    }
    return ''
  }
  const list = ref<ProjectType[]>([])
  const showModel = ref<boolean>(false)
  const activeCardData = ref<ProjectType>({})
  const loading = ref(false)
  const getDataList = async () => {
    const getConfigList = async (datasource: string) => {
      let reqdata: any = {
        application: 'page_designer',
        datasource
      }
      if (datasource === 'template' || datasource === 'project') {
        reqdata.domain_id = domainid()
      }
      const res = await getConfigApi(reqdata)
      return res.msg.map((item: any) => {
        return {
          ...item,
          content: JSON.parse(item.content),
          last_time: item.last_modify_time
        }
      })
    }
    const datasource = getDatasource()
    if (datasource === 'template') {
      // 租户模板
      const templates = await getConfigList('template')
      list.value = list.value.concat(templates)
    } else if (datasource === 'public_template') {
      // 公共模板 linku
      const publicTemplates = await getConfigList('public_template')
      list.value = publicTemplates
    } else {
      // 项目
      list.value = await getConfigList(datasource)
    }
    list.value = list.value.sort((a: ProjectType, b: ProjectType) => {
      return (a.content!.seq || 0) - (b.content!.seq || 0)
    })
  }

  // 新建
  const createHandle = async (val: ProjectType) => {
    loading.value = true
    const app_name = val.name || getUUID()
    const app_datasource = getDatasource()
    let data: any = {
      app_application: 'page_designer',
      app_datasource,
      app_name,
      name: val.content?.name || '新建项目',
      desc: val.content?.desc,
      domain_id: domainid()
    }
    if (val.id) {
      data = {
        ...data,
        ...val.content
      }
    } else {
      data = {
        ...data,
        release: false,
        type: app_datasource
      }
    }

    const res = await updateConfigApi(data)
    if (res.code === 200) {
      loading.value = false
      window.$message.success('操作成功')
      showModel.value = false
      getDataList()
    } else {
      loading.value = false
      window.$message.error('操作失败')
    }
  }

  // 修改
  const editHandle = async (val: ProjectType) => {
    activeCardData.value = val
    showModel.value = true
  }

  // 打开模态框
  const openModel = (cardData?: ProjectType) => {
    if (cardData) {
      activeCardData.value = cardData
    } else {
      activeCardData.value = {}
    }
    showModel.value = true
  }

  // 删除
  const deleteHandle = (cardData: any, index: number) => {
    goDialog({
      type: DialogEnum.DELETE,
      promise: true,
      onPositiveCallback: () => new Promise(res => setTimeout(() => res(1), 1000)),
      promiseResCallback: async (e: any) => {
        await deleteConfigApi({
          id: cardData.id,
          current_flag: 0
        })
        const pageres = await getConfigApi({
          application: 'page_designer',
          datasource: cardData.name
        })
        if (pageres.msg.length) {
          // 删除所有子页面
          await Promise.all(
            pageres.msg.map(async (item: ProjectType) => {
              await deleteConfigApi({ id: item.id, current_flag: 0 })
            })
          )
        }
        window.$message.success('删除成功')
        list.value.splice(index, 1)
      }
    })
  }

  // 生成新的项目及下页面
  const createNewProjectAndPages = async (params: any) => {
    const {
      app_datasource,
      app_name,
      oldProject,
      name,
      domain_id,
      page_use_source_id = false,
      show_success = true,
      isPublic = false
    } = params
    let data = {
      app_application: 'page_designer',
      app_datasource: app_datasource,
      app_name: app_name,
      domain_id: domain_id || domainid(),
      ...oldProject.content,
      name,
      release: false
    }
    data.type = app_datasource
    if (!isPublic) {
      delete data.from_public
      delete data.release_info
      delete data.release_domain
    }

    const res: any = await updateConfigApi(data)

    // 复制页面到新模板
    const pageres = await getConfigApi({
      application: 'page_designer',
      datasource: oldProject.name
    })
    if (pageres.msg.length) {
      const pagedata: any = {
        page_designer: {
          [app_name]: {}
        }
      }
      pageres.msg.forEach((item: any) => {
        const id = page_use_source_id ? item.name : getUUID()
        pagedata.page_designer[app_name][id] = { ...JSON.parse(item.content), domain_id: domain_id || domainid() }
      })
      await updateConfigApi(null, pagedata)
    }
    if (show_success && res.code === 200) {
      window['$message'].success('操作成功！')
      getDataList()
    }
  }

  // 设为模板
  const setModelHandle = async (cardData: ProjectType) => {
    const firstPath = getFirstPath()
    let datasource = firstPath === 'linku' ? 'public_template' : 'template'
    const app_name = getUUID()

    createNewProjectAndPages({
      app_datasource: datasource,
      oldProject: cardData,
      app_name,
      name: cardData.content?.name
    })
  }

  // 模板新建为项目
  const createProjectByTemplate = async (cardData: ProjectType) => {
    const firstPath = getFirstPath()
    let datasource = firstPath === 'linku' ? 'public_project' : 'project'
    const app_name = getUUID()
    createNewProjectAndPages({
      app_datasource: datasource,
      oldProject: cardData,
      app_name,
      name: cardData.content?.name
    })
  }

  const showSendModel = ref(false)
  // 发布
  const openSendModel = (cardData: ProjectType) => {
    activeCardData.value = cardData
    showSendModel.value = true
  }
  const sendHandle = async (cardData: ProjectType, selectDomains: any) => {
    loading.value = true
    // 定制项目发布到租户
    if (cardData.content?.release_domain) {
      // 创建或更新选中租户下的项目及页面
      const newProjectData = {
        ...cardData,
        content: {
          ...cardData?.content,
          type: 'project',
          from_public: true // 定制项目发布到租户后，不允许编辑
        }
      }
      delete newProjectData.content?.release_domain
      Promise.all(
        selectDomains.map(
          async (domain_id: string) =>
            await createNewProjectAndPages({
              app_datasource: 'project',
              app_name: cardData.content?.release_domain[domain_id].project_id,
              oldProject: newProjectData,
              name: cardData.content?.name,
              domain_id,
              page_use_source_id: true,
              show_success: false,
              isPublic: true
            })
        )
      )
        .then(async result => {
          // 保存公共项目的release_domain
          let data = {
            app_application: 'page_designer',
            app_datasource: cardData.datasource,
            app_name: cardData.name,
            domain_id: domainid(),
            ...cardData.content
          }

          await updateConfigApi(data)
          window['$message'].success('发布成功！')
          loading.value = false
          showSendModel.value = false
        })
        .catch(err => {
          console.log(err)
          loading.value = false
          window['$message'].error('发布失败！')
        })
    } else {
      // 租户项目发布到网关
      const pagesres = await getConfigApi({
        application: 'page_designer',
        datasource: cardData.name
      })
      const res = await uploadDataToGatawayApi(
        [{ ...cardData, content: JSON.stringify(cardData.content) }, ...pagesres.msg],
        {
          podName: cardData.content?.release_info.gateway_id,
          projectName: 'page-designer',
          scopeName: cardData.content?.release_info.scope,
          pathName: cardData.name,
          domainId: domainid(),
          stationId: cardData.content?.release_info.station_id,
          jsapiBaseUrl: ''
        }
      )
      if (res.code !== 200) {
        loading.value = false
        window['$message'].error('发布失败！')
        return
      }
      let data = {
        app_application: 'page_designer',
        app_datasource: cardData.datasource,
        app_name: cardData.name,
        ...cardData.content,
        domain_id: domainid()
      }

      await updateConfigApi(data)
      loading.value = false
      window['$message'].success('发布成功！')
      showSendModel.value = false
    }

    /* TODO:
     * 1. 添加公共模板menu,linku去掉我的模板
     * 2. 公共模板在租户里不可更改，只能创建项目/预览
     * 3. 全部项目改为我的项目，linku下改为定制项目
     * 4. 公共项目发布到租户后，再次发布会更新到租户，租户只可复制/预览
     * 5. 租户的项目发布时，将配置发布到网关上，后端出对应接口
     * 6. 公共项目发布时，记录发布了哪些租户与新生成项目的id，再次发布租户时存在则更新，不存在则创建
     */
  }

  // 导出项目
  const exportHandle = async (cardData: ProjectType) => {
    let data: any = deepCopy(cardData)
    delete data.content?.release_domain
    delete data.content?.release_info
    delete data.content?.from_public
    // 获取项目页面数据
    const pageres = await getConfigApi({
      application: 'page_designer',
      datasource: data.name
    })
    if (pageres.msg.length) {
      data.children = pageres.msg.map((item: ProjectType) => {
        return {
          ...item,
          content: JSON.parse(item?.content as any)
        }
      })
    }
    downloadTextFile(JSON.stringify(data), `LYView_项目_${data.content?.name}`, 'json')
  }

  // 导入项目
  const importProject = async () => {
    const res: any = await selectFile()
    const data = JSON.parse(res)
    if (data.datasource === 'public_project' || data.datasource === 'project') {
      const firstPath = getFirstPath()
      let app_datasource = firstPath === 'linku' ? 'public_project' : 'project'
      let app_name = getUUID()
      const reqdata = {
        page_designer: {
          [app_datasource]: {
            [app_name]: {
              domain_id: domainid(),
              ...data.content,
              release: false
            }
          },
          [app_name]: {}
        }
      }
      if (data.children && data.children.length) {
        reqdata.page_designer[app_name] = {}
        data.children.forEach((item: any) => {
          reqdata.page_designer[app_name][getUUID()] = {
            domain_id: domainid(),
            ...item.content
          }
        })
      }
      await updateConfigApi(null, reqdata)
      getDataList()
      window['$message'].success('导入成功！')
    } else {
      window.$message.error('选择导入文件内容错误')
    }
  }

  return {
    list,
    showModel,
    activeCardData,
    showSendModel,
    loading,
    getDataList,
    deleteHandle,
    createHandle,
    editHandle,
    getDatasource,
    openModel,
    setModelHandle,
    createProjectByTemplate,
    openSendModel,
    sendHandle,
    exportHandle,
    importProject
  }
}
